package com.example.medispider.utils;

import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.utils.HttpConstant;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class PageRequestBuilder {

    /**
     * 根据当前请求创建后续所有分页查找Request
     *
     * @param currentRequest 当前Request
     * @param pages          分页数量
     * @return 后续所有分页查找Request
     */
    public static ArrayList<Request> createPageRequests(Request currentRequest, int pages) {
        ArrayList<Request> requests = new ArrayList<>();
        String url = currentRequest.getUrl();
        HttpRequestBody requestBody = currentRequest.getRequestBody();
        if (requestBody != null) {
            String body = new String(requestBody.getBody());
            Map<String, Object> params = parseFormParams(body);
            for (int i = 2; i <= pages; i++) {
                // 页码参数
                params.put("pageNum", i);
                // 创建新 Request 对象
                Request newRequest = new Request(url);
                newRequest.setMethod(HttpConstant.Method.POST);
                HttpRequestBody httpRequestBody = HttpRequestBody.form(params, "utf-8");
                newRequest.setRequestBody(httpRequestBody);
                requests.add(newRequest);
            }
        } else {
            System.err.println("获取请求体失败！");
        }
        return requests;
    }

    /**
     * 解析表单格式的请求体参数
     */
    public static Map<String, Object> parseFormParams(String body) {
        Map<String, Object> params = new HashMap<>();
        String[] pairs = body.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            String key = keyValue[0];
            String value = ""; // 默认值
            if (keyValue.length == 2) {
                value = keyValue[1];
                value = URLDecoder.decode(value, StandardCharsets.UTF_8); // URL解码（如果需要）
            }
            params.put(key, value);
        }
        return params;
    }


}
